# Frontend Project Build Script (PowerShell 5.1 compatible)
param(
    [string]$Configuration = "production",
    [switch]$IncludeBackend,
    [string]$ProjectPath
)

$ErrorActionPreference = "Stop"
$script:hasErrors = $false

function Find-NearestFrontendProject {
    param([string]$StartPath = ".")
    
    # Find package.json files in current and parent directories
    $currentPath = $StartPath
    while ($currentPath -ne "") {
        $projects = Get-ChildItem -Path $currentPath -Filter "package.json" -Recurse | 
        Where-Object { $_.FullName -notlike "*\node_modules\*" }
        
        if ($projects) {
            return $projects[0]
        }
        
        $currentPath = Split-Path $currentPath -Parent
        if ($currentPath -eq $null) { break }
    }
    
    return $null
}

# Main execution flow
try {
    # Auto-detect project if not specified
    if (-not $ProjectPath) {
        $projectFile = Find-NearestFrontendProject
        if (-not $projectFile) {
            Write-Host "Error: No frontend project found in current or parent directories" -ForegroundColor Red
            $script:hasErrors = $true
            exit 1
        }
        $ProjectPath = $projectFile.Directory.FullName
    }

    Write-Host "Building frontend project: $ProjectPath" -ForegroundColor Cyan

    # Set unified output directory
    $outputDir = "$PSScriptRoot\BuildProject\frontend"
    $buildDir = "$outputDir\dist"

    # Create/clean output directory
    if (-not (Test-Path $outputDir)) {
        New-Item -ItemType Directory -Path $outputDir | Out-Null
    }
    else {
        Remove-Item "$outputDir\*" -Recurse -Force -ErrorAction SilentlyContinue
    }

    # Install dependencies
    Write-Host "Installing dependencies..." -ForegroundColor Cyan
    Set-Location $ProjectPath
    npm install
    if ($LASTEXITCODE -ne 0) { throw "Dependency installation failed" }

    # Build project
    Write-Host "Building project..." -ForegroundColor Cyan
    npm run build -- --mode $Configuration
    if ($LASTEXITCODE -ne 0) { throw "Build failed" }

    # Copy build output with debug logging
    Write-Host "Looking for build output in: $ProjectPath" -ForegroundColor Yellow
    $frontendDist = (Get-ChildItem -Path $ProjectPath -Directory | Where-Object { $_.Name -match "^(dist|build|out)$" } | Select-Object -First 1).FullName
    if (-not $frontendDist) {
        Write-Host "Available directories:" -ForegroundColor Yellow
        Get-ChildItem -Path $ProjectPath -Directory | ForEach-Object { Write-Host $_.FullName -ForegroundColor Yellow }
        throw "Could not find build output directory (dist/build/out)"
    }

    Write-Host "Found build output at: $frontendDist" -ForegroundColor Green
    Write-Host "Copying to: $buildDir" -ForegroundColor Green
    
    try {
        Copy-Item "$frontendDist\*" $buildDir -Recurse -Force -ErrorAction Stop
        Write-Host "Copy completed successfully" -ForegroundColor Green
    }
    catch {
        Write-Host "Copy failed: $_" -ForegroundColor Red
        throw $_
    }

    # Create zip package
    $projectName = [System.IO.Path]::GetFileNameWithoutExtension($ProjectPath)
    $zipFile = "$outputDir\$projectName-$(Get-Date -Format 'yyyyMMdd-HHmmss').zip"
    
    Write-Host "Creating package: $zipFile" -ForegroundColor Cyan
    Compress-Archive -Path "$buildDir\*" -DestinationPath $zipFile -Force
    if (-not $?) { throw "Package creation failed" }

    Write-Host "Build completed successfully!" -ForegroundColor Green
    Write-Host "Package created at: $(Resolve-Path $zipFile)" -ForegroundColor Green
}
catch {
    Write-Host "Build failed: $_" -ForegroundColor Red
    $script:hasErrors = $true
}

if ($script:hasErrors) {
    Write-Host "Build process encountered errors, please check above messages" -ForegroundColor Red
}

Read-Host "Press Enter to exit..."
